package com.ruoyi.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;


public class MailUtils {

    private static final Logger log = LoggerFactory.getLogger(MailUtils.class);

    /**
     * 发送邮件
     * @param title 邮件标题
     * @param content 邮件内容
     * @param toEmails 收件人
     */
    public static void sendMail(String title, String content, String[] toEmails){
        try {
            sendMailUtil(title,content, toEmails);
        }catch (Exception e){
            log.error("发送邮件失败,异常信息：{}", e);
        }
    }



    /**
     * 发送邮件
     * @param title 邮件标题
     * @param content 邮件内容
     * @param toEmails 收件人
     * @throws MessagingException
     */
    private static void sendMailUtil(String title, String content, String[] toEmails) throws MessagingException, UnsupportedEncodingException {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "smtp.neusoft.com");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.store.protocol", "pop3");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.debug","true");
        properties.setProperty("mail.smtp.ssl.trust", "smtp.neusoft.com");

        // 得到会话对象
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("hrad", "Rsh,123.");
            }
        }
        );
        // 获取邮件对象
        Message message = new MimeMessage(session);

        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress("hrad@neusoft.com", "报销管家", "UTF-8"));
        // 设置收件人邮箱地址
        InternetAddress[] addresses = new InternetAddress[toEmails.length];

        for(int i = 0, len = toEmails.length; i < len; i++){
            addresses[i] = new InternetAddress(toEmails[i]);
        }
        message.setRecipients(Message.RecipientType.TO, addresses);
        //message.setRecipient(Message.RecipientType.TO, new InternetAddress("zhou-qf_sr@neusiri.com"));
        // 设置邮件标题
        message.setSubject(title);
        // 设置邮件内容
        message.setContent(content + "<br/>", "text/html;charset=UTF-8");
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect();
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }



}
